<?php

namespace App\Model;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RoomShotoff extends BaseModel
{
    protected $table = 'room_shotoff_log';
    protected $primaryKey = 'id';
    public $timestamps = false;

    public function getImageAttribute($value)
    {
        if (!$value) return '';
        if (strpos($value[0], 'http:') !== false) {
            return $value;
        }
        return config('kkaudio.oss_url') . $value;
    }

    public function getList(Request $request, $room_id)
    {
        $dateType = $request->input('date_type','month');
        $dateTimeArray = $request->input('value');

        $where = $begin = $end = $format = '';
        if($dateType === 'month'){
            if($dateTimeArray[0]){
                $begin = date('Y-m',strtotime($dateTimeArray[0]));
            }
            if($dateTimeArray[1]){
                $end = date('Y-m',strtotime($dateTimeArray[1]));
            }
            $format = '%Y-%m';
        }
        if(empty($begin)){
            $begin = date('Y-m');
        }
        if(empty($end)){
            $end = date('Y-m');
        }
        $where .= " AND FROM_UNIXTIME(create_timestamp, '{$format}')>='$begin' AND FROM_UNIXTIME(create_timestamp, '{$format}')<='{$end}'";


        $sql = "SELECT * from zb_room_shotoff_log WHERE room_id={$room_id} $where  ORDER BY id asc ";
        $res = DB::connection($this->connection)->select($sql);
        $data = $this->objToArray($res);
        $total = count($data);
        if(!empty($data)){
            $user_ids = array_column($data ,'user_id');
            $shotoff_ids = array_column($data ,'shotoff_user_id');
            $all_user_ids = array_values(array_unique(array_merge($user_ids ,$shotoff_ids)));
            $users = DB::connection($this->connection)
                ->table('user')
                ->select('user_id','uuid' ,'nickname')
                ->whereIn('user_id' ,$all_user_ids)
                ->get();
            $users = $this->objToArray($users);
            $users = array_column($users ,null ,'user_id');
            foreach ($data as &$d){
                $d['user_uuid'] = $users[$d['user_id']]['uuid'];
                $d['user_name'] = $users[$d['user_id']]['nickname'];
                $d['shottff_uuid'] = $users[$d['shotoff_user_id']]['uuid'];
                $d['shottff_name'] = $users[$d['shotoff_user_id']]['nickname'];
                $d['date_time'] = date('Y-m-d H:i:s' ,$d['create_timestamp']);
            }
        }
        return ['total' => $total, 'data' => $data];
    }

}

